﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using PicStore.BLL.Interface;
using PicStore.Common.Ioc;
using PicStore.Web.Filters;
using PicStore.Common.Log;

namespace PicStore.Web.Controllers
{
    [HandleException(View = "Error")]
    public class BaseController : Controller
    {
        [Dependency]
        public IUserService UserService { get; set; }

        protected Model.User CurrentUser { get; set; }

        [Dependency]
        public ILog Log { get; set; }

        public const int PageSize = 20;

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            string userName = HttpContext.User.Identity.Name;
            if (string.IsNullOrEmpty(userName) == false)
            {
                CurrentUser = UserService.GetUser(userName);
                ViewData["RoleName"] = CurrentUser.Role.Name;
                if (!CurrentUser.IsAuthFor(controllerName, actionName))
                {
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "NoAuth",
                    };
                }
            }
            else
            {
                string url = controllerName.ToLower() + "/" + actionName.ToLower();
                if (url != "Account/login")
                {
                    filterContext.Result = new ViewResult
                    {
                        ViewName = "NoAuth",
                    };
                }
            }

            base.OnAuthorization(filterContext);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            //string actionName = filterContext.ActionDescriptor.ActionName;
            //string userName = HttpContext.User.Identity.Name;
            //var user = UserService.GetUser(userName);

            // 可以再次记录所有的用户的操作日志。
            //var logFunc = ObjectFactory.GetInstance<IAuditTrailFunc>();
            //logFunc.AddAuditTrail(user.Id,
            //    string.Format("操作参数是:{0}", ActionParameterExtention.ToString(filterContext.ActionParameters)),
            //    string.Format("{0}/{1}", controllerName, actionName));

            base.OnActionExecuting(filterContext);
        }

    }
}
